<script setup lang="ts">
import { reactive, ref, h } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { fetchMappingRuleList, deleteMappingRule } from '@/service/api';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import MappingRuleOperateDrawer from './modules/mapping-rule-operate-drawer.vue';

const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchMappingRuleList,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    ruleName: null,
    ruleCode: null,
    fileType: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 64
    },
    {
      key: 'ruleName',
      title: '规则名称',
      align: 'center',
      minWidth: 150
    },
    {
      key: 'ruleCode',
      title: '规则编码',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'fileType',
      title: '文件类型',
      align: 'center',
      width: 100,
      render: row => {
        const typeMap: Record<string, { label: string; type: NaiveUI.ThemeColor }> = {
          CSV: { label: 'CSV', type: 'success' },
          XLS: { label: 'XLS', type: 'info' },
          XLSX: { label: 'XLSX', type: 'info' },
          XML: { label: 'XML', type: 'warning' },
          JSON: { label: 'JSON', type: 'primary' },
          SQL: { label: 'SQL', type: 'error' }
        };
        const config = typeMap[row.fileType] || { label: row.fileType, type: 'default' };
        return h(NTag, { type: config.type }, { default: () => config.label });
      }
    },
    {
      key: 'fieldMappings',
      title: '字段映射数',
      align: 'center',
      width: 100,
      render: row => row.fieldMappings?.length || 0
    },
    {
      key: 'validationRules',
      title: '校验规则数',
      align: 'center',
      width: 100,
      render: row => row.validationRules?.length || 0
    },
    {
      key: 'createTime',
      title: $t('common.createTime'),
      align: 'center',
      width: 180
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      fixed: 'right',
      render: row => 
        h(NSpace, { justify: 'center' }, {
          default: () => [
            h(NButton, { 
              size: 'small', 
              type: 'primary', 
              onClick: () => handleEdit(row.id) 
            }, { default: () => $t('common.edit') }),
            h(NPopconfirm, { 
              onPositiveClick: () => handleDelete(row.id) 
            }, {
              default: () => $t('common.confirmDelete'),
              trigger: () => h(NButton, { 
                size: 'small', 
                type: 'error' 
              }, { default: () => $t('common.delete') })
            })
          ]
        })
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // @ts-ignore
} = useTableOperate(data, getData);

async function handleDelete(id: number) {
  await deleteMappingRule(id);
  onDeleted();
}

const fileTypeOptions = [
  { label: 'CSV', value: 'CSV' },
  { label: 'XLS', value: 'XLS' },
  { label: 'XLSX', value: 'XLSX' },
  { label: 'XML', value: 'XML' },
  { label: 'JSON', value: 'JSON' },
  { label: 'SQL', value: 'SQL' }
];
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :title="'数据映射规则'" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <NButton type="primary" size="small" @click="handleAdd">
          <icon-ic-round-plus class="mr-4px text-20px" />
          {{ $t('common.add') }}
        </NButton>
      </template>
      <div class="h-full flex-col">
        <NSpace class="pb-12px" justify="space-between">
          <NSpace>
            <NInput
              v-model:value="searchParams.ruleName"
              placeholder="规则名称"
              clearable
              @keyup.enter="getData"
            />
            <NInput
              v-model:value="searchParams.ruleCode"
              placeholder="规则编码"
              clearable
              @keyup.enter="getData"
            />
            <NSelect
              v-model:value="searchParams.fileType"
              placeholder="文件类型"
              clearable
              :options="fileTypeOptions"
              class="w-120px"
            />
          </NSpace>
          <NSpace align="center" :size="18">
            <NButton size="small" type="primary" @click="getData">
              <icon-ic-round-search class="mr-4px text-16px" />
              {{ $t('common.search') }}
            </NButton>
            <NButton size="small" @click="resetSearchParams">
              <icon-ic-round-refresh class="mr-4px text-16px" />
              {{ $t('common.reset') }}
            </NButton>
          </NSpace>
        </NSpace>
        <NDataTable
          v-model:checked-row-keys="checkedRowKeys"
          :columns="columns"
          :data="data"
          size="small"
          :flex-height="!mobilePagination"
          :scroll-x="1200"
          :loading="loading"
          remote
          :row-key="row => row.id"
          :pagination="mobilePagination"
          class="sm:h-0 sm:flex-1-hidden"
        />
      </div>
    </NCard>
    <MappingRuleOperateDrawer
      v-model:visible="drawerVisible"
      :operate-type="operateType"
      :row-data="editingData"
      @submitted="getData"
    />
  </div>
</template>

<style scoped></style>
